package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/app/task"
	"server/internal/database"
	"server/internal/pkg/response"
	"strconv"
)

// ConfigApi 用户管理
var ConfigApi = new(configApi)

type configApi struct {
	model.Config
}

// Detail 单条
func (a configApi) Detail(c *gin.Context) {
	group := c.Query("group")
	Db := database.DB

	detail := configApi{}
	Db.Model(&detail).Where("`group` =?", group).First(&detail)
	info := make(map[string]any)
	json.Unmarshal([]byte(detail.Value), &info)
	response.SuccessData(c, info, "")
}

// Edit 编辑
func (a configApi) Edit(c *gin.Context) {
	Db := database.DB
	var param configApi
	info := make(map[string]any) //注意该结构接受的内容
	err := c.ShouldBindJSON(&info)
	if err != nil {
		response.Fail(c, err, "参数错误")
		return
	}
	str, _ := json.Marshal(info)
	if Db.Model(&param).Where("`group` = ?", info["group"]).Update("value", string(str)).Error == nil {
		response.Success(c, "", "修改成功")

	} else {
		response.Fail(c, "", "修改失败")
	}

}

// 读取 定时任务状态
func (a configApi) taskStatus(c *gin.Context) {

	data := make(map[string]any)
	data["time"] = task.TaskStatus.Time
	data["status"] = task.TaskStatus.Status
	response.Success(c, "", "ok")
}

// 修改定时任务状态
func (a configApi) taskStatusEdit(c *gin.Context) {
	var param task.Status
	//注意该结构接受的内容
	err := c.ShouldBindJSON(&param)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "err": err.Error()})
		response.Fail(c, err.Error(), "参数错误")
	}
	m, _ := strconv.Atoi(param.Time)
	if m <= 0 {
		response.Fail(c, err.Error(), "间隔时间不能未0分钟")

		return
	}

	if param.Status == "start" && task.TaskStatus.Status == "start" {
		response.Fail(c, err.Error(), "定时任务正在运行，请关闭后重试")
		return
	}
	task.TaskStatus.Time = param.Time
	if param.Status == "start" {
		err = task.Start()
		if err != nil {
			response.Fail(c, err.Error(), "定时任务启动失败")
			return
		} else {
			response.Success(c, "", "定时任务已开启")
			return
		}
	}

	if param.Status == "stop" {
		task.Stop()
		response.Success(c, "", "定时任务已关闭")
	}

}
